package com.SampleCustomWidget;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

public class CustomWidget extends LinearLayout{

    GridView mItemGrid = null;
    Context mContext = null;
    
    public CustomWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCustomWidget(context);
    }

    public CustomWidget(Context context) {
        super(context);
        initCustomWidget(context);
    }
    
    void initCustomWidget(Context context) {
        mContext = context;
        
        String infService = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li = (LayoutInflater) getContext().getSystemService(infService);

        View v = li.inflate(R.layout.layoutwidget, this, false);
        addView(v);    
        
        mItemGrid = (GridView) findViewById(R.id.griditem);

        setAdapter(new ImageAdapter(mContext));
        
        setFocusable(true);
        setFocusableInTouchMode(true);
    }
    
    public void setAdapter(ListAdapter adapter) {
        mItemGrid.setAdapter(adapter);
    }
    
    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter(Context c) {
            mContext = c;
        }
        
        @Override
        public int getCount() {
            return mThumbIds.length;
        }
        
        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) { 
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(45, 45));
                imageView.setAdjustViewBounds(false);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
                imageView.setBackgroundColor(Color.BLUE);
            } else {
                imageView = (ImageView) convertView;
            }

            imageView.setImageResource(mThumbIds[position]);
            return imageView;
        }

        private Context mContext;

        private Integer[] mThumbIds = {
                R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
                R.drawable.sample_thumb_2, R.drawable.sample_thumb_3,  //1
        };

		

    }
}
